package ${cfg.baseServiceImplPackage};


import ${cfg.baseMapperPackage}.${table.beanName}DAO;
import ${cfg.baseDbBeanPackage}.domain.${table.beanName};
import ${cfg.baseServicePackage}.${table.beanName}Service;
import static  com.mryt.supplier.center.constant.Constant.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mryt.dt.base.PageReq;
import org.springframework.util.Assert;
import com.mryt.api.domain.ApiResult;
import com.mryt.dt.base.Page;
import java.util.List;
import static  com.mryt.supplier.center.service.impl.SupplierServiceFunctional.failure;

@Service
@Slf4j
public class ${table.beanName}ServiceImpl  implements ${table.beanName}Service{

    @Autowired
    private ${table.beanName}DAO dao;

    @Override
    public ${table.beanName} getById(int id) {
        return dao.get(id);
    }


     @Override
    public ApiResult save(${table.beanName} entity) {
        Assert.notNull(entity, "参数不能为空");

        try {
            if (entity.getId() != null) {
                dao.updateIgnoreNull(entity);
            } else {
                init(entity);
                dao.add(entity);
            }
        } catch (DuplicateKeyException e) {
            log.error("已存在:{}", e);
            return failure.apply("已存在");
        } catch (Exception e) {
            log.error("失败:{}", e);
            return failure.apply("创建失败");
        }

        return ApiResult.success();
    }


    private void init(${table.beanName} entity){
        entity.setStatus(VALID_STATUS);
    }


    @Override
    public ApiResult enable(int id, int status) {
        ${table.beanName} entity = new ${table.beanName}();
        entity.setId(id);
        entity.setStatus(status);
        dao.updateIgnoreNull(entity);
        return ApiResult.success();
    }


    @Override
    public Page<${table.beanName}> page(PageReq<${table.beanName}> req) {
        if (req.getModel() == null) {
            req.setModel(new ${table.beanName}());
        }

        PageInfo<${table.beanName}> pageInfo = PageHelper.startPage(req.getPageNo(), req.getPageSize())
            .doSelectPageInfo(() -> dao.findByConditionLike(req.getModel()));

        Page<${table.beanName}> page = new Page<>();
        page.setTotal(pageInfo.getTotal());
        page.setList(pageInfo.getList());
        return page;
    }


    @Override
    public List<${table.beanName}> findAll() {
        ${table.beanName} entity = new ${table.beanName}();
        entity.setStatus(VALID_STATUS);
        return dao.findByConditionLike(entity);
    }


    }
